<!--
 * @Author: Li Zengkun
 * @Date: 2022-09-13 19:23:45
 * @LastEditors: Li Zengkun
 * @LastEditTime: 2022-09-17 14:18:11
 * @Description: 
-->
<template>
  <div class="content">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>分类管理</span>
          <el-button icon="Plus" @click="handleAdd" type="primary"
            >添加分类</el-button
          >
        </div>
      </template>

      <!-- tree -->
      <el-tree
        :data="categoryList"
        :props="defaultProps"
        highlight-current
        @node-click="handleNodeClick"
        node-key="id"
      >
        <template #default="{ node, data }">
          <div class="tree-node">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                icon="Edit"
                @click.stop="handleEdit(data)"
                size="small"
                type="primary"
                >编辑</el-button
              >
              <el-button
                v-if="data.parent_id === 0"
                icon="Plus"
                @click.stop="handleAdd(data)"
                size="small"
                type="success"
                >添加</el-button
              >
              <el-button
                icon="Delete"
                @click.stop="handleRemove(data)"
                size="small"
                type="danger"
                >删除</el-button
              >
            </span>
          </div>
        </template>
      </el-tree>
    </el-card>
  </div>
</template>
 
<script setup>
import { ref, reactive } from "vue";
import { category } from "@/api";
import { eachReplaceKey } from "@/assets/js/";

let categoryList = ref((await category.list({ type: "tree" })).data);
console.log(categoryList.value);
let defaultProps = { label: "name" };

/**
 * @description: 删除分类
 * @return {*}
 * @param {*} data
 */
const handleRemove = (data) => {
  ElMessageBox.confirm(
    `<p>你是否要删除 <b>${data.name}</b> 分类?</p>`,
    "确认",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      let { status, msg } = await category.remove({ id: data.id });
      if (status) {
        if (data.parent_id === 0) {
          categoryList.value.splice(
            categoryList.value.findIndex((item) => item.id === data.id),
            1
          );
        } else {
          let curArr = categoryList.value.find(
            (item) => item.id === data.parent_id
          ).children;
          curArr.splice(
            curArr.findIndex((item) => item.id === data.id),
            1
          );
        }
      }
      ElMessage({
        type: status ? "success" : "error",
        message: msg,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

/**
 * @description: 添加标签
 * @return {*}
 */
const handleAdd = (data) => {
  console.log(data.name);
  ElMessageBox.prompt(
    !data.name ? "请输入一级分类" : `请输入 ${data.name} 的子分类`,
    "添加分类",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }
  )
    .then(async ({ value }) => {
      console.log(value);
      let res = await category.add({
        name: value,
        parent_id: data.id || 0,
      });
      console.log(res);
      if (res.status) {
        if (data.name) {
          let targetTree = categoryList.value.find(
            (item) => item.id === data.id
          );
          let curArr = targetTree.children;
          console.log(curArr);
          if (curArr) {
            curArr.push({ id: res.data.id, name: value, parent_id: data.id });
          } else {
            targetTree.children = [];
            targetTree.children.push({
              id: res.data.id,
              name: value,
              parent_id: data.id,
            });
          }
          return;
        } else {
          categoryList.value.push({
            id: res.data.id,
            name: value,
            parent_id: 0,
            children: [],
          });
          return;
        }
      }
      ElMessage({
        type: res.status ? "success" : "error",
        message: res.msg,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

/**
 * @description: 修改分类名
 * @return {*}
 * @param {*} data
 */
const handleEdit = (data) => {
  ElMessageBox.prompt("请修改分类名", "编辑分类", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPlaceholder: data.name,
  })
    .then(async ({ value }) => {
      let res = await category.edit({
        id: data.id,
        name: value,
        parent_id: data.parent_id,
      });
      if (res.status) {
        if (data.parent_id === 0) {
          categoryList.value.find((item) => item.id === data.id).name = value;
        } else {
          let curArr = categoryList.value.find(
            (item) => item.id === data.parent_id
          ).children;
          curArr.find((item) => item.id === data.id).name = value;
        }
      }
      ElMessage({
        type: res.status ? "success" : "error",
        message: res.msg,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};
</script>

<style lang='less' scoped>
.tree-node {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

